package com.vf.cloud.paas.common.datasource.config;

import java.sql.Connection;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import com.vf.cloud.paas.app.agent.common.mapping._MappingKit;

@Primary
@Configuration
public class ActiveRecordPluginConfig implements InitializingBean, DisposableBean {

	@Value("${mysql.port}")
	private String MYSQLPort;

	@Value("${agent.enabled}")
	private boolean agentEnabled;

	@Value("${master.enabled}")
	private boolean masterEnabled;

	private DruidPlugin druidPlugin;
	private ActiveRecordPlugin arp;

	public void destroy() throws Exception {
		druidPlugin.stop();
		arp.stop();
	}

	public void afterPropertiesSet() throws Exception {
		init();
	}

	public void init() {
		druidPlugin = new DruidPlugin("jdbc:mysql://127.0.0.1:" + MYSQLPort
				+ "/paas?characterEncoding=utf8&useUnicode=true&characterEncoding=utf-8&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC&nullNamePatternMatchesAll=true&autoReconnect=true",
				"root", "vfcloud@2022");
		arp = new ActiveRecordPlugin("Paas", druidPlugin);
		arp.setShowSql(false);
		arp.setTransactionLevel(Connection.TRANSACTION_READ_COMMITTED);
		arp.getEngine().setToClassPathSourceFactory();
		arp.setDialect(new MysqlDialect());

		if (masterEnabled) {
			com.vf.cloud.paas.app.master.common.mapping._MappingKit.mapping(arp);
		}
		if (agentEnabled) {
			_MappingKit.mapping(arp);
		}

		druidPlugin.start();
		arp.start();
	}

}
